package Controller

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"log"
	"m/Global"
	"m/model"
	"m/response"
	"net/http"
)

func RegisterStudent(context *gin.Context) {
	// 获取参数
	fmt.Println("开始获取参数")
	var requestStudent = model.Student{}
	json.NewDecoder(context.Request.Body).Decode(&requestStudent)
	sno := requestStudent.Sno
	sname := requestStudent.Sname
	sdate := requestStudent.Sdate
	spassword := requestStudent.Spassword
	samount := requestStudent.Samount
	// 数据验证
	fmt.Println("开始数据验证")
	fmt.Println("传来的注册信息：", sno, sname, sdate, spassword, samount)
	if len(sno) < 1 {
		//response.Response(context, http.StatusUnprocessableEntity, 422, nil, "学号必须大于0位！")
		//context.JSON(http.StatusUnprocessableEntity, gin.H{"code":422, "msg":"学号必须大于2位！"})
		context.JSON(200, gin.H{
			"code":200,
			"msg":"学号不能为空！",
		})
		return
	}
	if len(sname) == 0 {
		//sname = util.RandomString(-1)
		return
	}
	if len(spassword) < 6 {
		//response.Response(context, http.StatusUnprocessableEntity, 422, nil, "密码不能少于6位！")
		//context.JSON(http.StatusUnprocessableEntity, gin.H{"code":422, "msg":"密码不能少于6位！"})
		context.JSON(200, gin.H{
			"code":200,
			"msg":"密码不能少于6位！",
		})
		return
	}
	fmt.Println(sno, sname, sdate, spassword, samount)
	log.Println(sno, sname, spassword, sdate, samount)
	log.Println(sno)
	//判断学号是否存在
	//tempSno, err := strconv.Atoi(sno)
	if isSnoExists(Global.Db, sno) == true {
		//response.Response(context, http.StatusUnprocessableEntity, 422, nil, "学号已经存在！")
		//context.JSON(http.StatusUnprocessableEntity, gin.H{"code":422, "msg":"学号已经存在！"})
		context.JSON(200, gin.H{
			"code":200,
			"msg":"此学号已被注册！",
		})
		// 直接返回，不执行下面的create了
		return
	}
	// 创建用户

	//if err != nil {
	//	fmt.Println("错误")
	//	return
	//}
	//hasedPassword, err := bcrypt.GenerateFromPassword([]byte(spassword), bcrypt.DefaultCost)
	//if err != nil {
	//	context.JSON(http.StatusInternalServerError, gin.H{"code":500, "msg":"加密错误！"})
	//	// 直接返回，不执行下面的create了
	//	return
	//}
	newStudent := model.Student{
		Sno: sno,
		Sname: sname,
		Sdate: sdate,
		Spassword: spassword,
		Samount: samount,
	}
	Global.Db.Create(&newStudent)


	// 发放token
	token, err := Global.ReaeaseTokec(newStudent)
	if err != nil {
		context.JSON(200, gin.H{
			"code":200,
			"msg":"系统异常",
		})
		log.Printf("token generate error:%v\n", err)
		return
	}
	// 返回结果
	//context.JSON(200, gin.H{
	//	"code":200,
	//	"data":gin.H{"token":token},
	//	"msg":"登陆成功！",
	//})


	// 返回结果
	//context.JSON(200, gin.H{
	//	"code":200,
	//	"msg":"注册成功！",
	//})
	response.Success(context, gin.H{"token":token}, "注册成功！")
}

func StudentLogin(context *gin.Context)  {
	fmt.Println("进入studentlogin")
	// 使用map获取请求的参数
	//var requestMap = make(map[string]string)
	//json.NewDecoder(context.Request.Body).Decode(&requestMap)
	// 使用结构体来请求参数
	var requestStudent = model.Student{}
	json.NewDecoder(context.Request.Body).Decode(&requestStudent)//法一
	//context.Bind(&requestStudent)//法二
	fmt.Println("获取到的数据：", requestStudent.Sno, requestStudent.Spassword)
	Global.Sno = requestStudent.Sno
	// 获取参数
	sno := requestStudent.Sno
	spassword := requestStudent.Spassword
	// 数据验证
	//if len(sno) < 2 {
	//	context.JSON(http.StatusUnprocessableEntity, gin.H{"code":422, "msg":"学号必须大于2位！"})
	//	return
	//}
	if len(sno) < 1 {
		context.JSON(200, gin.H{
			"code":200,
			"msg":"学号不能为空",
		})
		return
	}

	if len(spassword) < 6 {
		fmt.Println("密码不能少于6位！", len(spassword), len(requestStudent.Spassword))
		context.JSON(200, gin.H{
			"code":200,
			"msg":"密码不能少于6位",
		})
		return
	}
	// 学号是否存在
	var student model.Student
	//tempSno, err := strconv.Atoi(sno)
	//fmt.Println("转换后的tempSno：", tempSno)

	Global.Db.Where("sno = ?", sno).First(&student)
	fmt.Println("student.Sno=", student.Sno)
	if student.Sno == "" {
		//context.JSON(http.StatusUnprocessableEntity, gin.H{"code":422, "msg":"用户不存在！！"})
		context.JSON(200, gin.H{
			"code":200,
			"msg":"用户不存在",
		})
		return
	}
	// 判断密码是否正确
	//if err := bcrypt.CompareHashAndPassword([]byte(student.Spassword), []byte(spassword)) ; err != nil {
	//	fmt.Println(student.Spassword, spassword)
	//	context.JSON(http.StatusBadRequest, gin.H{"code":400, "msg":"密码错误"})
	//	return
	//}
	if student.Spassword != spassword {
		fmt.Println(student.Spassword, spassword)
		context.JSON(200, gin.H{
			"code":200,
			"msg":"密码错误",
		})
		return
	}
	// 发放token
	token, err := Global.ReaeaseTokec(student)
	if err != nil {
		context.JSON(200, gin.H{
			"code":200,
			"msg":"token发放失败?",
		})
		log.Printf("token generate error:%v\n", err)
		return
	}
	// 返回结果
	//context.JSON(200, gin.H{
	//	"code":200,
	//	"data":gin.H{"token":token},
	//	"msg":"登陆成功！",
	//})
	response.Success(context, gin.H{"token":token}, "登陆成功")
}

func Info(context *gin.Context)  {
	student, _:= context.Get("user")
	context.JSON(http.StatusOK, gin.H{
		"code":200,
		"data":gin.H{
			"user":student,
		},
	})
}

func ShowStudent(context *gin.Context) {
	fmt.Println("进入showstudent")
	var student []model.Student
	err := Global.Db.Find(&student).Error
	if err != nil {
		fmt.Println("查询全体学生出错！")
		return
	}
	fmt.Println("数据库查到的全体学生信息：", student)
	context.JSON(http.StatusOK, student)
}

func CountStudent(context *gin.Context)  {
	// 调用存储过程
	var count int
	Global.Db.Raw("select count_student()").First(&count)
	fmt.Println("学生数量：", count)
	context.JSON(200, gin.H{
		"code":200,
		"msg":"返回学生数量成功",
		"data":count,
	})
}

func ShowStudentSelect(context *gin.Context) {
	fmt.Println("进入showstudentselect")
	var requestStudent = model.Student{}
	json.NewDecoder(context.Request.Body).Decode(&requestStudent)
	fmt.Println("即将搜索学号：", requestStudent.Sno)

	if len(requestStudent.Sno) < 1 {
		fmt.Println("学号不能为空！", len(requestStudent.Sno))
		context.JSON(http.StatusUnprocessableEntity, gin.H{
			"code":422,
			"msg":"学号为空",
		})
		return
	}
	// 学号是否存在
	var student []model.Student
	Global.Db.Where("sno = ?", requestStudent.Sno).First(&student)
	fmt.Println("student.Sno=", student[0].Sno)
	if student[0].Sno == "" {
		context.JSON(http.StatusUnprocessableEntity, gin.H{
			"code":422,
			"msg":"找不到此学生！",
		})
		return
	}
	context.JSON(http.StatusOK, student)
}

func isSnoExists(db *gorm.DB, sno string) bool {
	var student model.Student
	//tempSno, err := strconv.Atoi(sno)
	//fmt.Println("转换后的tempSno：", tempSno)

	err := db.Where("sno = ?", sno).First(&student).Error
	if err != nil {
		fmt.Println("err执行")
		return false
	}
	if student.Sno != "" {//找到重复的学号
		fmt.Println("找到的重复学号为：", student.Sno)
		fmt.Println("执行了if")
		return true
	} else {//没找到重复的学号
		fmt.Println("执行了else")
		return false
	}
}
